package model

import (
	"encoding/json"
	"github.com/shopspring/decimal"
	"matching/enum"
	"matching/utils"
	"strings"
)


type Order struct {
	Action    enum.OrderAction `json:"action"`
	Symbol    string           `json:"symbol"`
	OrderId   string           `json:"orderId"`
	Side      enum.OrderSide   `json:"side"`
	Type      enum.OrderType   `json:"type"`
	Amount    decimal.Decimal  `json:"amount"`     //下单数量，市价单表示下单额
	TradedAmount decimal.Decimal `json:"tradedAmount"`  //已成交数量
	Price     decimal.Decimal  `json:"price"`
	Timestamp int64            `json:"timestamp"`
	UserId string				`json:"userId"`
	Turnover decimal.Decimal	`json:"turnover"`  //已成交额
	Status enum.OrderStatus		`json:"status"`  //状态
	TriggerPrice decimal.Decimal `json:"triggerPrice"`  //触发价
}

func (order *Order) ToJson() string {
	data, err := json.Marshal(order)
	if err==nil {
		return string(data)
	}else {
		return ""
	}
}

func (order *Order) ToMap() map[string]interface{} {
	value :=make(map[string]interface{})
	value["Action"]=order.Action.String()
	value["Symbol"]=order.Symbol
	value["OrderId"]=order.OrderId
	value["Side"]=order.Side.String()
	value["Type"]=order.Type.String()
	value["Amount"]=order.Amount.String()
	value["TradedAmount"]=order.TradedAmount.String()
	value["Price"]=order.Price.String()
	value["Timestamp"]=order.Timestamp
	value["UserId"]=order.UserId
	value["Turnover"]=order.Turnover.String()
	value["Status"]=order.Status.String()
	value["TriggerPrice"]=order.TriggerPrice.String()
	return value
}


func (order *Order) IsCompleted() bool {
	if order.IsMarket() &&order.Side==enum.SideBuy  {
		if (order.Amount.Sub(order.Turnover)).LessThanOrEqual(utils.MinNumber){
			return true
		}else {
			return false
		}
	}else {
		if (order.Amount.Sub(order.TradedAmount)).LessThanOrEqual(utils.MinNumber) {
			return true
		}else {
			return false
		}
	}
}

func (order *Order) IsMarket() bool {
	if order.Type==enum.Market ||order.Type==enum.MarketTop5 ||order.Type==enum.MarketTop10 {
		return true
	}else {
		return false
	}
}


func (order *Order) ToStringLine() string {
	value :=make(map[string]interface{})
	value["Action"]=order.Action.String()
	value["Symbol"]=order.Symbol
	value["OrderId"]=order.OrderId
	value["Side"]=order.Side.String()
	value["Type"]=order.Type.String()
	value["Amount"]=order.Amount.String()
	value["TradedAmount"]=order.TradedAmount.String()
	value["Price"]=order.Price.String()
	value["Timestamp"]=order.Timestamp
	value["UserId"]=order.UserId
	value["Turnover"]=order.Turnover.String()
	value["Status"]=order.Status.String()
	value["TriggerPrice"]=order.TriggerPrice.String()
	return strings.Join([]string{order.Action.String(), order.Symbol,order.OrderId,order.Side.String(),order.Type.String(),
		order.Amount.String(),order.TradedAmount.String(),order.Price.String(),order.UserId,order.Turnover.String(),order.Status.String(),order.TriggerPrice.String()}, ",")
}